#include "visit.h"

void visit_funcDef(ASTNode* node, SymbolTable* s, Module* m, BasicBlock* bb, string ident, string ret_type){
    ASTNode* child_funcFParams = node -> children[1];
    ASTNode* child_block = node -> children[3];

    
    string funcName = ident;
    string funcType = ret_type;

    // pair.first是参数类型，pair.second是参数名
    vector<pair<string, string>> paramNames = visit_funcFParams(child_funcFParams, s, bb);

    Type* RetType;
    if(funcType == "void"){
        RetType = m -> get_void_type();
    }
    else if(funcType == "int"){
        RetType = m -> get_int32_type();
    }
    else if(funcType == "float"){
        RetType = m -> get_float_type();
    }
    else {
        std::cerr << "visit_funcDef :" << "FuncType 不支持的类型: " << funcType << std::endl;
        throw std::invalid_argument(std::string("visit_funcDef :") + "不支持的类型: " + funcType);
    }
    vector<Type*> param_types;
    for (auto paramName : paramNames) {
        Type* param_type;
        if(paramName.first == "int"){
            param_type = m -> get_int32_type(); // 假设参数类型为int
        }
        else if(paramName.first == "float"){
            param_type = m -> get_float_type();
        }
        else {
            std::cerr << "visit_funcDef :" << "不支持的类型: " << paramName.first << std::endl;
            throw std::invalid_argument(std::string("visit_funcDef :") + "不支持的类型: " + paramName.first);
        }
        param_types.push_back(param_type);
    }

    FunctionType* func = FunctionType::get(RetType, param_types);

    // 创建函数
    Function* function = Function::create(func, funcName, m);
    s->addSymbol(funcName, FUNC, funcType, 0, NULL, NULL, function, NULL);

    BasicBlock* new_bb = new BasicBlock(m, funcName + "_ENTRY", function, false);
    s -> enterScope();
    visit_block(child_block, s, m, new_bb);
    s -> exitScope();
}